function work_pusher(url,bodyx) {
    const tip = document.getElementById("te_tip");
    fetch(url, {
        method: 'POST',
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(bodyx)
    }).then(response => response.json()).then(data => {
        if (data.success === true) {
            location.reload();
        } else {
            tip.innerText = "失败: " + data.err;
            tip.style.display = "block";
        }
    }).catch((error) => {
       tip.innerText = "错误: " + data.err;
       tip.style.display = "block";
    });
}
function add_pusher(){
    const new_id = document.getElementById("new-id").value;
    const new_key = document.getElementById("new-key").value;
    const tip = document.getElementById("te_tip");
    if(new_id === "" || new_key === "") {
        tip.innerText = "ID和Key均不能为空";
        tip.style.display = "block";
        return;
    }
    work_pusher("/api/addpusher",{"id": new_id,"key": new_key});
}

function del_pusher(id){
    if(!confirm(`确定删除推流器${id}吗？`)) return;
    work_pusher("/api/delpusher", {"id": id});
}

function query_pusher() {
    get_channels(data=>{
        const channels = data.data;
        for(let c in channels) {
            const ya = document.getElementById("status-"+c);
            if(channels[c]["pushing"]) {
                ya.innerText="正在推流"
                const btn = document.getElementById("start-"+c);
                if(btn!=null) btn.remove()
            }else{
                ya.innerText="未推流"
                const btn = document.getElementById("stop-"+c);
                if(btn!=null) btn.remove()
            }
        }
    })
}

function start_push(id) {work_pusher("/api/startpusher",{"id": id})}
function stop_push(id) {work_pusher("/api/stoppusher",{"id": id})}

query_pusher();